package net.lzzy.practices.aspects;

import net.lzzy.practices.entities.User;
import net.lzzy.practices.services.UserService;
import net.lzzy.practices.utils.AspectUtil;
import net.lzzy.practices.utils.JwtUtil;
import net.lzzy.practices.web.models.ApiResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.UUID;

/**
 * @author m
 */
@Aspect //切面
@Component //该注解为
public class AdminAspect {
    private UserService service;

    //    UserService service;
    //定义切入点
    @Pointcut("execution(* net.lzzy.practices.web.admin.UserApiController.*(..))")
    public  void adminPoint(){}

    @Around("adminPoint()")
    public ApiResult aroundAdminControls(ProceedingJoinPoint point) throws Throwable {
        String token= AspectUtil.getTokrn(point);
        String uid= JwtUtil.verifyToken(token);
        //token 参数的3种形式： 1。直接列在方法参数种 2.使用了Info参数类BaseIofo  3.使用 JSONObject
        if(uid==null){
            return  new ApiResult(false,"认证信息错误",null);
        }

        User user= service.getById(UUID.fromString(uid));
        if(user == null){
            return  new ApiResult(false,"认证信息错误",null);
        }
        int[] allowRoles= new int[]{User.TYPE_ADMIN};
        if(Arrays.stream(allowRoles).noneMatch(role->role==user.getType())){
            return  new ApiResult(false,"没有该权限",null);
        }

        return   (ApiResult)point.proceed();

    }
}
